<template>
  <div class="clearfix">
    <a-upload
      name="image"
      v-model:file-list="fileList"
      :headers="headers"
      :action="baseUrl"
      :progress="progress"
      :max-count="maxCount"
      @preview="handlePreview"
      :customRequest="(file:any) => uploadFile(file)"
    >
      <slot />
    </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, toRefs } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import { storage } from '@/utils/storage'
import apis from '@/apis'
const {
  permission: { upload }
} = apis
const emit = defineEmits(['getImageInfo'])

const fileList = ref([])
const getBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

const progress: UploadProps['progress'] = {
  strokeColor: {
    '0%': '#108ee9',
    '100%': '#87d068'
  },
  strokeWidth: 3,
  format: (percent: any) => `${parseFloat(percent.toFixed(2))}%`,
  class: 'test'
}

interface ImageInfo {
  maxCount?: number //设置最多可以上传的图片数量
  fileUrl?: string //上传到后端的路径
  imgType: string
}
const props = withDefaults(defineProps<ImageInfo>(), {
  maxCount: 1,
  fileUrl: '',
  /**
  0: 杂项图片保存，不知道放哪里，就放在这里
  - 1: 视频相关图片
  - 2: 图集相关图片
  - 3: 文章小说相关图片
  - 4: 广告相关图片
  */
  imgType: '0'
})
const { maxCount, fileUrl, imgType } = toRefs(props)
const baseUrl = ref(import.meta.env.VITE_BASE_URL + fileUrl.value)
console.log('baseUrl: ', baseUrl)
interface HeaderInfo {
  Authorization: string
}
const headers = reactive<HeaderInfo>({
  Authorization: 'Bearer ' + storage.get('token')
})
const previewImage = ref('')
const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj)
  }
  previewImage.value = file.url || file.preview
}
const imageType = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
// 检查图片格式和图片大小
const beforeUpload = (file: any) => {
  // console.log('file: ', file)
  // const img_size = storage.get('img_size')
  // console.log('img_size: ', img_size)
  // //图片格式限制为 jpeg、png
  // const isJpgOrPng = imageType.includes(file.type)
  // if (!isJpgOrPng) {
  //   message.error('只支持后缀为 .jpg .jpeg .png .bmp .gif 的图片')
  //   return false
  // }
  // //图片大小限制为 2M以内
  // const isLt10M = file.size / 1024 / 1024 <= 10
  // if (!isLt10M) {
  //   message.error('图片大小不能超过10MB，请重新上传')
  //   return false
  // }
  // return isJpgOrPng && isLt10M
}
// const handleChange = (info: any) => {
// console.log('info: ', info)
// const file = info.file as any
// const fileList = info.fileList as any
// if (info.file.status === 'done') {
//   console.log(file, fileList, 'fileData')
//   message.success(`${info.file.name} 上传成功`)
// } else if (info.file.status === 'error') {
//   message.error(`${info.file.name} 上传失败`)
// }
// emit('getImageInfo', file.name)
// }
const uploadFile = (file: any) => {
  // beforeUpload(file.file)//后端判断
  console.log('file123: ', file)
  const formData = new FormData()
  formData.append('file', file.file)
  formData.append('img_type', imgType.value)
  upload(formData)
    .then((res: any) => {
      file.onSuccess()
      message.success('图片上传成功')
      emit('getImageInfo', res.data.url)
    })
    .catch((error) => {
      file.onError()
      // emit('getImageInfo', res.url)
    })
}
</script>

<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

:deep(.ant-upload.ant-upload-select-picture-card) {
  width: 422px;
  display: flex;
  align-items: center;
  height: auto;
  border: none;
}

.w-359 {
  width: 359px;
}

:deep(.ant-upload-list) {
  display: none;
}
</style>
